﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Json;
using System.Net;
using System.Net.Http;
using System.IO;
using System.Windows.Forms;
using ANGFLib;

namespace ANGF
{
    public static class WebApiWrapper
    {
        private static WebApiResults common(WebApiParameters value, string accessToken)
        {
            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(WebApiParameters));

                MemoryStream ms = new MemoryStream();
                serializer.WriteObject(ms, value);

                CookieContainer cookieContainer = new CookieContainer();
                using (var handler = new HttpClientHandler() { UseCookies = true, CookieContainer = cookieContainer })
                using (var client = new HttpClient(handler) { BaseAddress = new Uri("https://angfwebplayer4.azurewebsites.net/") })
                {
                    if (!string.IsNullOrWhiteSpace(accessToken))
                    {
                        var cookieCollcetion = new CookieCollection();
                        cookieCollcetion.Add(new Cookie(".AspNet.ApplicationCookie", accessToken));
                        handler.CookieContainer.Add(new Uri("https://angfwebplayer4.azurewebsites.net/"), cookieCollcetion);
                    }

                    var s = Encoding.UTF8.GetString(ms.ToArray());
                    var content = new StringContent(s, Encoding.UTF8, "application/json");
                    // POSTでリクエスト
                    var result = client.PostAsync("https://angfwebplayer4.azurewebsites.net/Api/CommonApi", content).Result;

                    DataContractJsonSerializer serializer2 = new DataContractJsonSerializer(typeof(WebApiResults));

                    byte[] bytes = result.Content.ReadAsByteArrayAsync().Result;

                    var r = Encoding.UTF8.GetString(bytes);
                    System.Diagnostics.Trace.WriteLine(r);

                    MemoryStream ms2 = new MemoryStream(bytes);
                    WebApiResults results = (WebApiResults)serializer2.ReadObject(ms2);

                    return results;
                }
            }
            catch (Exception e)
            {
                var r2 = new WebApiResults();
                r2.Success = false;
                r2.ErrorMessage = e.ToString();
                return r2;
            }
        }
        public static string AccessToken = null;

        private static void disable(Form form)
        {
            UI.Actions.CallAnyMethod(() =>
            {
                form.Cursor = Cursors.WaitCursor;
                form.Enabled = false;
            });
        }
        private static void enable(Form form)
        {
            UI.Actions.CallAnyMethod(() =>
            {
                form.Cursor = Cursors.Default;
                form.Enabled = true;
            });
        }

        private static WebApiResults commonAccess(Form form, WebApiParameters req)
        {
            disable(form);
            var r = common(req, AccessToken);
            enable(form);
            if (!r.Success)
            {
                AccessToken = UI.Actions.GetAccessToken();
                if (string.IsNullOrWhiteSpace(AccessToken)) return null;
                disable(form);
                r = common(req, AccessToken);
                enable(form);
                return r.Success ? r : null;
            }
            return r;
        }

        public static bool ConfirmIdPassword(Form form)
        {
            var req = new WebApiParameters();
            req.Command = WebCommands.ConfirmIdPassword;
            return commonAccess(form, req) != null;
        }

        public static string[] ListLoadFiles(Form form)
        {
            var req = new WebApiParameters();
            req.Command = WebCommands.ListLoadFiles;
            req.Extention = General.FileExtention;
            var r = commonAccess(form, req);
            if (r == null) return null;
            Array.Sort(r.Names);
            return r.Names;
        }
        public static string[] ListSaveFiles(Form form)
        {
            var req = new WebApiParameters();
            req.Command = WebCommands.ListSaveFiles;
            req.Extention = General.FileExtention;
            var r = commonAccess(form, req);
            if (r == null) return null;
            Array.Sort(r.Names);
            return r.Names;
        }
        public static string[] ListAutoLoadFiles(Form form)
        {
            var req = new WebApiParameters();
            req.Command = WebCommands.ListAutoLoadFiles;
            req.Extention = General.FileExtention;
            var r = commonAccess(form, req);
            if (r == null) return null;
            Array.Sort(r.Names);
            return r.Names;
        }
        public static byte[] LoadFile(Form form, string category, string filename)
        {
            var req = new WebApiParameters();
            req.Command = WebCommands.LoadFile;
            req.Name = filename;
            req.Extention = General.GetExtentionByCategory(category);
            req.Category = category;
            var r = commonAccess(form, req);
            if (r != null) return r.Body;
            return null;
        }
        public static string SaveFile(Form form, string category, string filename, byte[] body)
        {
            var req = new WebApiParameters();
            req.Command = WebCommands.SaveFile;
            if (category == WebApiCategorys.Normal)
                req.Name = filename.Substring(0, 7) + General.GenerateSuggestedFileNameWithoutExt(false);
            else
                req.Name = filename;
            req.Extention = General.GetExtentionByCategory(category);
            req.Category = category;
            req.Body = body;
            var r = commonAccess(form, req);
            if (r == null) return null;
            if (r.Names == null) return null;
            if (r.Names.Length < 1) return null;
            return r.Names[0];
        }
    }
}
